<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->
    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('入库单')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>
      <a-tabs v-model="activeKey">
        <a-tab-pane key="noticed" tab="入库通知单">
          <div class="table-page-search-wrapper">
            <a-form layout="inline" @keyup.enter.native="searchQuery">
              <a-row :gutter="24">
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <a-form-item label="">
                    <j-input type="like" v-model="ext1"></j-input>
                    <!--                    <a-input placeholder="" type="like" v-model="ext1"></a-input>-->
                    <!--                    <j-dict-select-tag type="list" v-model="queryParam.businessType"-->
                    <!--                                       dictCode="business_type" placeholder="请选择业务类型"/>-->
                  </a-form-item>
                </a-col>
                <a-col :xl="6" :lg="7" :md="8" :sm="24">
                  <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                    <a-button type="primary" @click="searchNoticed" icon="search">搜索</a-button>
                    <!--                    <a-button type="primary" @click="searchResetTab1" icon="reload" style="margin-left: 8px">重置</a-button>-->
                    <a-button type="primary" @click="addStoraged" icon="reload" style="margin-left: 8px">添加入库单</a-button>
                  </span>
                </a-col>
              </a-row>
            </a-form>
          </div>
          <a-table
            ref="noticeTable"
            size="middle"
            bordered
            :rowKey="(record,index)=>{return index}"
            class="j-table-force-nowrap"
            :scroll="{x:true}"
            :columns="table1.columns"
            :dataSource="table1.dataSource"
            :pagination="table1.ipagination"
            :loading="table1.loading"
            :rowSelection="{selectedRowKeys: table1.selectedRowKeys,onChange: onSelectChangeTab1}"
            @change="handleTableChange">
          </a-table>
        </a-tab-pane>
        <a-tab-pane key="ru" tab="入库单">
          <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
            <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
            <a style="margin-left: 24px" @click="onClearSelected">清空</a>
            <a-popover title="自定义列" trigger="click" placement="leftBottom" style="float: right">
              <template slot="content">
                <a-checkbox-group @change="onColSettingsChange" v-model="settingColumns" :defaultValue="settingColumns">
                  <a-row>
                    <template v-for="(item,index) in defColumns">
                      <template v-if="item.key!='rowIndex'&& item.dataIndex!='action'">
                        <a-col :span="12"><a-checkbox :value="item.dataIndex">{{ item.title }}</a-checkbox></a-col>
                      </template>
                    </template>
                  </a-row>
                </a-checkbox-group>
              </template>
              <a><a-icon type="setting" />自定义列</a>
            </a-popover>
          </div>
          <a-table
            ref="table"
            size="middle"
            bordered
            :rowKey="(record,index)=>{return index}"
            class="j-table-force-nowrap"
            :scroll="{x:true}"
            :columns="columns"
            :dataSource="dataSource"
            :pagination="ipagination"
            :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
            @change="handleTableChange"
            :rowClassName="(record, index) => (record.isPrinted === 1 ? 'print-row' : 'row-class')"
          >
            <template slot="htmlSlot" slot-scope="text">
              <div v-html="text"></div>
            </template>
            <template slot="imgSlot" slot-scope="text,record">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
              <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
            </template>
            <template slot="fileSlot" slot-scope="text">
              <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
              <a-button
                v-else
                :ghost="true"
                type="primary"
                icon="download"
                size="small"
                @click="downloadFile(text)">
                下载
              </a-button>
            </template>

            <span slot="action" slot-scope="text, record">
          <a @click="handleEdit(record)">编辑</a>

          <a-divider type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetail(record)">详情</a>
              </a-menu-item>
              <a-menu-item>
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.detailId)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
          </a-table>
        </a-tab-pane>
      </a-tabs>
    </div>
    <buss-storage-modal ref="modalForm" @ok="modalFormOk"/>
  </a-card>
</template>

<script>

  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import BussStorageModal from './modules/BussStorageModal'
  import '@/assets/less/TableExpand.less'
  import { filterDictTextByCache, filterMultiDictText } from '@/components/dict/JDictSelectUtil'
  import { filterObj } from '@/utils/util'
  import { deleteAction, getAction } from '@api/manage'

  export default {
    name: "BussStorageList",
    mixins:[JeecgListMixin],
    components: {
      BussStorageModal
    },
    data () {
      return {
        description: '入库单管理页面',
        isorter: {
          column: 'id',
          order: 'desc',
        },
        ext1: '',
        activeKey: 'noticed',
        table1:{
          selectedRowKeys: [],
          selectionRows: [],
          loading: false,
          columns: [
            {
              title: '#',
              dataIndex: '',
              key:'rowIndex',
              width:60,
              align:"center",
              customRender:function (t,r,index) {
                return parseInt(index)+1;
              }
            },
            {
              title:'编号',
              align:"center",
              dataIndex: 'code',
              customRender:  (text, record, index) => {
                const obj = {
                  children: [<span>{text}</span>],
                  attrs: {},
                };
                // 判断是否需要合并行
                if (index > 0 && record.code === this.table1.dataSource[index - 1].code) {
                  obj.attrs.rowSpan = 0;
                } else {
                  obj.attrs.rowSpan = this.table1.dataSource.filter(item => item.code === record.code).length;
                }
                return obj;
              }
            },
            {
              title:'供应商',
              align:"center",
              dataIndex: 'supplierName'
            },
            {
              title:'批次号',
              align:"center",
              dataIndex: 'lotNumber'
            },
            {
              title:'质检单编号-',
              align:"center",
              dataIndex: ''
            },
            {
              title:'质检结果-',
              align:"center",
              dataIndex: ''
            },
            {
              title:'质检数量-',
              align:"center",
              dataIndex: ''
            },
            {
              title:'原料编号',
              align:"center",
              dataIndex: 'materialCode'
            },
            {
              title:'原料名称',
              align:"center",
              dataIndex: 'materialName'
            },
            {
              title:'规格',
              align:"center",
              dataIndex: 'spec'
            },
            {
              title:'单位',
              align:"center",
              dataIndex: 'unit_dict'
            },
            {
              title:'采购数量',
              align:"center",
              dataIndex: 'procurementNum'
            },
            {
              title:'原发数',
              align:"center",
              dataIndex: 'originalNum'
            },
            {
              title:'实收数量',
              align:"center",
              dataIndex: 'actualNum'
            },
            {
              title:'制单日期',
              align:"center",
              dataIndex: 'createTime'
            },
            {
              title:'制单人',
              align:"center",
              dataIndex: 'createBy'
            },
            {
              title:'进厂日期',
              align:"center",
              dataIndex: 'factoryTime'
            },
            {
              title:'生产日期',
              align:"center",
              dataIndex: 'createDate'
            },
            {
              title:'限用日期',
              align:"center",
              dataIndex: 'expiryDate'
            },
            {
              title:'让步接受数量-',
              align:"center",
              dataIndex: ''
            },
            {
              title:'入库数量-',
              align:"center",
              dataIndex: ''
            },
            {
              title:'物料批号',
              align:"center",
              dataIndex: 'materialLotNum'
            },
            {
              title:'库位',
              align:"center",
              dataIndex: 'erpLocationName'
            },
            {
              title:'宝洁供应商编号',
              align:"center",
              dataIndex: 'bjSupplierCode'
            },
            {
              title:'宝洁供应商采购订单号',
              align:"center",
              dataIndex: 'bjProcurementCode'
            },
            {
              title:'宝洁供应商名称',
              align:"center",
              dataIndex: 'bjSupplierName'
            },
          ],
          dataSource: [],
          ipagination: {
            current: 1,
            pageSize: 30,
            pageSizeOptions: ['10', '20', '30'],
            showTotal: (total, range) => {
              return range[0] + "-" + range[1] + " 共" + total + "条"
            },
            showQuickJumper: true,
            showSizeChanger: true,
            total: 0
          },
        },
        // 表头
        columns: [],
        settingColumns: [],
        // 表头
        defColumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'编号',
            align:"center",
            dataIndex: 'code'

          },
          {
            title:'行项目',
            align:"center",
            dataIndex: 'rowNum'
          },
          {
            title:'类型',
            align:"center",
            dataIndex: 'storageType'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title:'物料种类',
            align:"center",
            dataIndex: 'materialTypeName'
          },
          {
            title:'物料编号',
            align:"center",
            dataIndex: 'materialCode'
          },
          {
            title:'物料名称',
            align:"center",
            dataIndex: 'materialName'
          },
          {
            title:'物料规格',
            align:"center",
            dataIndex: 'spec'
          },
          {
            title:'车间',
            align:"center",
            dataIndex: 'workshop_dictText'
          },
          {
            title:'仓库',
            align:"center",
            dataIndex: 'erpWarehouseName'
          },
          {
            title:'仓位',
            align:"center",
            dataIndex: 'erpLocationName'
          },
          {
            title:'入库数量',
            align:"center",
            dataIndex: 'num'
          },
          {
            title:'单位',
            align:"center",
            dataIndex: 'meUnit'
          },
          {
            title:'辅助数量',
            align:"center",
            dataIndex: 'supportNum'
          },
          {
            title:'辅助单位',
            align:"center",
            dataIndex: 'supportUnit'
          },
          {
            title:'供应商编号',
            align:"center",
            dataIndex: 'supplierCode'
          },
          {
            title:'供应商名称',
            align:"center",
            dataIndex: 'supplierName'
          },
          {
            title:'批次号',
            align:"center",
            dataIndex: 'batchNum'
          },
          {
            title:'物料批号',
            align:"center",
            dataIndex: 'materialLotNum'
          },
          {
            title:'入库日期',
            align:"center",
            dataIndex: 'warehouseDate'
          },
          {
            title:'生产日期',
            align:"center",
            dataIndex: 'createDate'
          },
          {
            title:'限用日期',
            align:"center",
            dataIndex: 'expiryDate'
          },
          {
            title:'让步接受数量==',
            align:"center",
            dataIndex: ''
          },
          {
            title:'关联单据编号',
            align:"center",
            dataIndex: 'superiorCode'
          },
          {
            title:'质检单据编号===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'质检人===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'质检结果===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'质检时间===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'当前状态===',
            align:"center",
            dataIndex: 'status'
          },
          {
            title:'经办人===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'经办部门===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'经办日期===',
            align:"center",
            dataIndex: ''
          },
          {
            title:'制单人',
            align:"center",
            dataIndex: 'createBy'
          },
          {
            title:'制单日期',
            align:"center",
            dataIndex: 'createTime'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' },
          }
        ],
        url: {
          list: "/business/bussStorage/list",
          delete: "/business/bussStorage/delete",
          deleteBatch: "/business/bussStorage/deleteBatch",
          exportXlsUrl: "/business/bussStorage/exportXls",
          importExcelUrl: "business/bussStorage/importExcel",
          noticedUrl: "/business/bussStorageNotice/list"
        },
        dictOptions:{},
        superFieldList:[],
      }
    },
    created() {
      this.columns = this.defColumns
      this.getSuperFieldList();
      this.loadNoticedData();
      this.initColumns();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      }
    },
    mounted() {

    },
    watch:{

    },
    methods: {
      batchDel: function () {
        if (!this.url.deleteBatch) {
          this.$message.error("请设置url.deleteBatch属性!")
          return
        }
        if (this.selectedRowKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
          return;
        } else {
          var ids = "";
          for (var a = 0; a < this.selectedRowKeys.length; a++) {
            ids += this.selectionRows[a].detailId + ",";
          }
          var that = this;
          this.$confirm({
            title: "确认删除",
            content: "是否删除选中数据?",
            onOk: function () {
              that.loading = true;
              deleteAction(that.url.deleteBatch, {ids: ids}).then((res) => {
                if (res.success) {
                  //重新计算分页问题
                  that.reCalculatePage(that.selectedRowKeys.length)
                  that.$message.success(res.message);
                  that.loadData();
                  that.onClearSelected();
                } else {
                  that.$message.warning(res.message);
                }
              }).finally(() => {
                that.loading = false;
              });
            }
          });
        }
      },
      dataProcessingForRowspan(list, key) {
        let repeatCount = 1;
        let startIndex = 0;
        list.forEach((item, index) => {
          if (index < list.length - 1 && item.code === list[index+1].code) {
            item.rowSpan = 0;
            repeatCount += 1
          } else {
            list[startIndex].rowSpan = repeatCount;
            startIndex = index + 1;
            repeatCount = 1;
          }
        })
      },
      addStoraged(){
        const rows = this.table1.selectionRows;
        if(rows.length == 0){
          this.$message.warn('请选择入库通知单！')
          return;
        }
        let row = rows[0];
        let newarray = rows.filter(item=> item.id === row.id );
        console.log(newarray)
        console.log(rows)
        if(newarray.length != rows.length){
          this.$message.warn('请选择同一个入库通知单');
          return;
        }
        // const supplierId = rows[0].supplierId
        // const newrows = rows.filter(item=> item.supplierId === supplierId );
        // if(newrows.length != rows.length){
        //   this.$message.warn('一个入库通知单单只能是同一个供应商！')
        //   return;
        // }
        //
        this.$refs.modalForm.add();
        this.$refs.modalForm.title = "新增";
        this.$refs.modalForm.disableSubmit = false;
        // 添加入库通知单
        this.$nextTick(()=>{
          // this.$refs.modalForm.$refs.realForm.procSelectRows = rows
          this.$refs.modalForm.$refs.realForm.addNoticed(rows)
        })
      },
      onSelectChangeTab1(selectedRowKeys, selectionRows) {
        // console.log('数量',selectedRowKeys.length)
        // if( selectedRowKeys.length > 1 && selectedRowKeys.length > this.table1.dataSource.length){
        //   let row = selectionRows[0]
        //   const newrows = this.table1.selectionRows.filter(item=> item.code === row.code );
        //   if(newrows.length !== selectionRows.length){
        //     this.$message.warn('只能选择同一个入库通知单！')
        //     selectedRowKeys.pop();
        //     return;
        //   }
        // }
        // if(selectedRowKeys.length > this.table1.selectedRowKeys.length){
        //   let row = selectionRows[0]
        //   this.table1.dataSource.forEach((item,index)=>{
        //     if(item.code ===  row.code){
        //       selectedRowKeys.push(index)
        //     }
        //   })
        // }
        this.table1.selectedRowKeys = selectedRowKeys;
        this.table1.selectionRows = selectionRows;
      },
      searchNoticed(){
        this.loadNoticedData()
      },
      getNoticeQueryField() {
        //TODO 字段权限控制
        var str = "id,";
        this.table1.columns.forEach(function (value) {
          str += "," + value.dataIndex;
        });
        return str;
      },
      getNoticedQueryParams() {
        //获取查询条件
        var param = {};
        param.field = this.getNoticeQueryField();
        param.ext1 = this.ext1
        param.pageNo = this.table1.ipagination.current;
        param.pageSize = this.table1.ipagination.pageSize;
        param.status = 3
        param.detailStatus = '0,2'
        return filterObj(param);
      },
      loadNoticedData(){
        //加载数据 若传入参数1则加载第一页的内容
        // if (arg === 1) {
        //   this.ipagination.current = 1;
        // }
        // var params = {}
        var params = this.getNoticedQueryParams();//查询条件

        this.table1.loading = true;
        getAction(this.url.noticedUrl, params).then((res) => {
          if (res.success) {
            //update-begin---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------

            // let result = res.result.records || res.result;
            // this.dataProcessingForRowspan(result, 'code');

            this.table1.dataSource =  res.result.records || res.result;
            this.table1.dataSource = this.table1.dataSource.map(item=>({
              ...item, selectAll: true
            }))
            if (res.result.total) {
              this.table1.ipagination.total = res.result.total;
            } else {
              this.table1.ipagination.total = 0;
            }
            //update-end---author:zhangyafei    Date:20201118  for：适配不分页的数据列表------------
          } else {
            this.$message.warning(res.message)
          }
        }).finally(() => {
          this.table1.loading = false

        })
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'string',value:'code',text:'编号',dictCode:''})
        fieldList.push({type:'int',value:'storageType',text:'入库类型',dictCode:''})
        fieldList.push({type:'string',value:'superiorCode',text:'上级单号',dictCode:''})
        fieldList.push({type:'date',value:'storageDate',text:'入库日期'})
        fieldList.push({type:'string',value:'supplierId',text:'供应商id',dictCode:''})
        fieldList.push({type:'string',value:'lotNumber',text:'批次号',dictCode:''})
        this.superFieldList = fieldList
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';

  /*.print-row {*/
  /*  !*color: gray;*!*/
  /*  background-color: green;*/
  /*}*/
</style>
<style >


.print-row {
  /*color: gray;*/
  background-color: #a8c9ee !important;
}
:deep(.ant-table-tbody .ant-table-row-hover > td) {
  background-color: #fff !important;
}


/*.ant-table-tbody > tr:hover:not(.ant-table-expanded-row) > td,.ant-table-row-hover,.ant-table-row-hover>td{*/
/*  background-color: transparent !important;*/
/*}*/

/* .ant-table-row-hover{*/
/*  background-color: transparent !important;*/
/*}*/


/*.ant-table-tbody > tr:hover:not(.ant-table-expanded-row) > td,.ant-table-row-hover,.ant-table-row-hover>td{*/
/*  background-color: transparent !important;*/
/*}*/

/*.ant-table-row-hover{*/
/*  background-color: transparent !important;*/
/*}*/
/*.print-row:hover {*/
/*  background-color: green !important; !* 悬停时的背景色 *!*/
/*}*/
/*.row-class:hover,*/


/*.ant-table .print-row:hover {*/
/*  background-color: blue !important; !* 悬停状态的背景色 *!*/
/*}*/



/*:deep(table tbody tr:hover>td) {*/
/*  background-color: transparent  !important;*/
/*}*/

/*:deep(table tbody .ant-table-row-selected>td) {*/
/*  background-color: transparent !important;*/
/*}*/

/*.print-row:hover {*/
/*  background-color: transparent !important; !* 悬停时的背景色 *!*/
/*}*/
/*.ant-table-row:hover {*/
/*  background-color: #e6f7ff; !* 修改悬停行的背景色 *!*/
/*}*/
</style>

